<?php
namespace qgauth\datascope;
use common\components\RedisHelper;
use yii\helpers\ArrayHelper;

/**
 * 数据权限增删查改接口的控制器，依赖coreController
 */
trait RoleDataScopeController
{
    protected function getModelClass(): string
    {
        return RoleDataScopeService::class;
    }

    /**
     * 列表
     * @return void
     * @throws \ReflectionException
     */
    public function actionList()
    {
        $params = $this->mergeListParams();
        if (empty($params['role_id'])) {
            $this->error('请选择角色!');
        }

        $service = new RoleDataScopeService();

        $list = $service::getListOfPage($params);

        return $this->success(
            '列表',
            ArrayHelper::merge(
                ['data' => ArrayHelper::toArray($list['models'])],
                ['totalNums' => $list['pages']->totalCount]
            )
        );
    }

    public function actionAdd()
    {
        $post = \Yii::$app->request->post();
        $User = \Yii::$app->controller->_user;
        $post['company_id'] = $User->company_id;
        $post['create_user_id'] = $User->id;
        $post['update_user_id'] = $User->id;
        if (\Yii::$app->request->getIsPost()) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $lock = RedisHelper::getLock('lock:RoleDataScopeAdd' . $User->id, 15);

                $model = new RoleDataScopeService();
                $model->attributes = $post;
                if (!$model->save())
                    throw new \Exception('新增失败!' . $model::outError($model->getErrors()), 422);

                $transaction->commit();
                RedisHelper::unLock($lock);
                $this->success('新增成功!', ['id' => $model->id]);
            } catch (\Exception $exception) {
                $transaction->rollBack();
                if (!empty($lock)) RedisHelper::unLock($lock);
                $this->error($exception->getMessage());
            }
        } else {
            $this->error('参数异常!');
        }
    }

    /**
     * 编辑
     * @return void
     * @throws \common\extensions\RedisException
     */
    public function actionEdit()
    {
        $post = \Yii::$app->request->post();

        $user = \Yii::$app->controller->_user;

        $company_id = $user->company_id;

        if(\Yii::$app->request->getIsPost())
        {
            $transaction = \Yii::$app->db->beginTransaction();

            try
            {
                if (empty($post['id'])) {
                    $this->error('参数有误');
                }
                $id = $post['id'];
                $lock = RedisHelper::getLock('lock:RoleDataScopeEdit' . $id, 15);

                $service = new RoleDataScopeService();

                /** @var RoleDataScopeService $role_data_scope */
                $role_data_scope = $service::getModels($id, $company_id);

                if(empty($role_data_scope)) throw new \Exception('没有找到记录');

                $role_data_scope->setAttributes($post);

                if(!$role_data_scope->save())
                {
                    throw new \Exception('编辑失败!' . $role_data_scope::outError($role_data_scope->getErrors()), 422);
                }

                $transaction->commit();

                RedisHelper::unLock($lock);

                return $this->success('编辑成功!', ['id' => $role_data_scope->id]);
            }
            catch(\Exception $exception)
            {
                $transaction->rollBack();

                if(!empty($lock))
                {
                    RedisHelper::unLock($lock);
                }
                return $this->error($exception->getMessage());
            }
        }
        else
        {
            return $this->error('参数异常!');
        }
    }
}